<template>
  <div class="charts_box mt-20">
    <div :class="['charts_box_title flex-between', tableColumn.length === 1 && tableData.length && 'charts_box_title_hiden']">
      <div class="charts_box_left">
        <svg-icon
          v-for="(item, index) in leftIconList"
          :key="item"
          :class="[leftIconList.findIndex((i: any) => i === leftActive) === index && 'active-icon']"
          :icon-class="
            leftIconList.findIndex((i: any) => i === leftActive) === index ? `${item}2` : `${item}1`
          "
          @click.stop="handelIcon(item)"
        />
      </div>
      <!--待办-->
      <div class="charts_box_right">
        <svg-icon></svg-icon>
        <svg-icon></svg-icon>
        <svg-icon></svg-icon>
        <svg-icon></svg-icon>
      </div>
    </div>
    <!--表格-->
    <div v-show="leftActive === 'bg'">
      <!-- height="500"  -->
      <app-table class="mt-16" :data="tableData" v-if="tableColumn.length > 1">
        <el-table-column
          v-for="item in tableColumn"
          :key="item.name"
          :prop="item.prop"
          :label="item.label"
          min-width="180"
          max-width="220"
        >
        </el-table-column>
      </app-table>
      <!--一条数据展示-->
      <div v-else-if="tableColumn.length === 1 && tableData.length" class="table-tip-text">
        <div class="table-tip-text-num">{{ tableData[0][tableColumn[0].prop] }}</div>
        <div class="table-tip-text-des">{{ item.queryText }}</div>
      </div>
      <!--暂无数据-->
      <div v-else style="padding-top: 10px;">
        暂无数据
      </div>
    </div>
    <!--图表-->
    <div v-show="leftActive !== 'bg'">
      <div ref="chartsRef" :style="style" v-resize:500="changeChartSize"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, nextTick, onBeforeUnmount, ref, computed, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps<{ queryResult: any; item: any }>()
const chartsRef = ref()
const leftIconList = ref<any>([])
const leftActive = ref('')

const tableColumn = computed(() => {
  return (
    props.queryResult?.queryColumns?.map((item: any) => {
      return {
        prop: item.bizName,
        label: item.name
      }
    }) || []
  )
})

const tableData = computed(() => {
  return props.queryResult?.queryResults || []
})

const isShowEcharts = computed(() => {
  if (!Array.isArray(tableColumn.value) || !Array.isArray(tableData.value) || !tableColumn.value.length || !tableData.value.length) {
    return false
  }
  let isStr = false
  let isNum = false
  Object.keys(tableData.value[0]).forEach((i) => {
    if (typeof(tableData.value[0][i]) === 'string'){
      isStr = true
    } else if (typeof(tableData.value[0][i]) === 'number'){
      isNum = true
    }
  })
  const isTableData = tableData.value.length > 1 && tableData.value.length < 30
  return isStr && isNum && isTableData && tableColumn.value.length === 2 
})

watch(
  () => isShowEcharts.value,
  (newValue) => {
    if (newValue) {
      leftIconList.value = ['zxt', 'zzs', 'zzh', 'bt', 'bg']
    } else {
      leftIconList.value = ['bg']
    }
    leftActive.value = leftIconList.value[0]
    newValue && initChart()
  },
  {
    deep: true,
    immediate: true
  }
)

const style = ref({
  height: '516px',
  width: '100%'
})

function handelIcon(item: any) {
  leftActive.value = item
  isShowEcharts.value && initChart()
}

function getChartsOptions() {
  const chartType = leftActive.value
  const primaryColor = '#3067EF'
  const xAxisData: any = []
  const seriesData: any = []

  tableData.value.forEach((el: any) => {
    const tempKeys = Object.keys(el)
    if(tempKeys.length === 2) {
      tempKeys.forEach((k: any)=> {
        if(isNaN(el[k])){
          xAxisData.push(el[k])
        } else {
          seriesData.push(el[k])
        }
      })
    }
  });

  switch (chartType) {
    case 'zxt': // 折线图（竖向）
      return {
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {},
        series: [
          {
            type: 'line',
            data: seriesData,
            smooth: true,
            itemStyle: { color: primaryColor },
            lineStyle: { color: primaryColor },
            label: {
              show: true,
              position: 'top',
              formatter: (params: any) => params.value.toLocaleString() // 数据标签格式化
            }
          }
        ]
      }

    case 'zzs': // 柱状图（竖向）
      return {
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {},
        series: [
          {
            type: 'bar',
            data: seriesData,
            itemStyle: { color: primaryColor, borderRadius: [10,10,0,0]},
            lineStyle: { color: primaryColor },
            barWidth: 20,
            label: {
              show: true,
              position: 'top',
              formatter: (params: any) => params.value.toLocaleString() // 数据标签格式化
            }
          }
        ]
      }

    case 'zzh': // 柱状图（横向）
      return {
        tooltip: { trigger: 'axis' },
        yAxis: {
          type: 'category',
          data: xAxisData
        },
        xAxis: {},
        series: [
          {
            type: 'bar',
            data: seriesData,
            itemStyle: { color: primaryColor, borderRadius: [0,10,10,0] },
            lineStyle: { color: primaryColor },
            barWidth: 20,
            label: {
              show: true,
              position: 'right',
              formatter: (params: any) => params.value.toLocaleString() // 数据标签格式化
            }
          }
        ]
      }

    case 'bt': // 饼图
      return {
        tooltip: { trigger: 'item' },
        legend: {
          data: xAxisData,
          top: '2%',
        },
        series: [
          // {
          //   type: 'pie',
          //   data: seriesData.map((val: any, idx: any) => ({ name: xAxisData[idx], value: val })),
          //   radius: '50%'
          // },
          {
            type: 'pie',
            radius: ['30%', '55%'], // 改成环形图，内圆40%，外圆70%
            data: seriesData.map((val: any, idx: any) => ({ name: xAxisData[idx], value: val })),
            label: {
              show: true,
              formatter: '{b}: {c} ({d}%)', // 显示名称、数值、百分比
              color: '#333'
            },
            labelLine: {
              lineStyle: {
                color: '#999'
              },
              smooth: true
            }
          }
        ]
      }

    default:
      return {} // 默认空配置
  }
}

function initChart() {
  if (chartsRef.value) {
    let myChart = echarts?.getInstanceByDom(chartsRef.value)
    if (myChart === null || myChart === undefined) {
      myChart = echarts.init(chartsRef.value)
    }
    const option = getChartsOptions()
    myChart.setOption(option, true)
  }
}

function changeChartSize() {
  echarts?.getInstanceByDom(chartsRef.value)?.resize()
}

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

onBeforeUnmount(() => {
  echarts.getInstanceByDom(chartsRef.value)?.dispose()
})
</script>
<style lang="scss" scoped>
.charts_box {
  overflow: hidden;
  margin-bottom: 20px;
  &_title {
    height: 40px;
    background: #f0f5ff;
  }
  &_left {
    font-size: 20px;
    padding-left: 20px;
    svg {
      margin-right: 20px;
      cursor: pointer;
    }
    .active-icon {
      color: #fff;
    }
  }
  .table-tip-text {
    background: #f0f5ff;
    border-radius: 0px 0px 0px 0px;
    padding: 12px 24px;
    display: inline-block;
    margin-top: 20px;
    box-sizing: border-box;
    min-width: 200px;
    .table-tip-text-num {
      min-width: 69px;
      height: 36px;
      font-family: DIN, DIN;
      font-weight: bold;
      font-size: 28px;
      color: #3067ef;
      line-height: 36px;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
    .table-tip-text-des {
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: #333333;
      line-height: 20px;
      text-align: left;
      font-style: normal;
      text-transform: none;
      margin-top: 8px;
    }
  }
}
.charts_box::-webkit-scrollbar-track-piece {
  background-color: rgba(0, 0, 0, 0);
  border-left: 1px solid rgba(0, 0, 0, 0);
}

.charts_box::-webkit-scrollbar {
  width: 5px;
  height: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

.charts_box::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.5);

  background-clip: padding-box;

  -webkit-border-radius: 5px;

  -moz-border-radius: 5px;

  border-radius: 5px;

  min-height: 28px;
}

.charts_box::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.5);

  -webkit-border-radius: 5px;

  -moz-border-radius: 5px;

  border-radius: 5px;
}

:deep(.el-table th.el-table__cell) {
  background-color: #cddeff;
  color: #000;
}
.charts_box_title_hiden{
  display: none;
}
</style>
